package top.haijunit.common.response.data;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.*;
import lombok.experimental.Accessors;

import java.io.Serial;
import java.io.Serializable;
import java.time.Instant;
import java.time.ZonedDateTime;

/**
 * 统一返回Rest风格的数据结构
 *
 * @author zhanghaijun
 * @date 2024/6/6 13:21
 * @description [一句话描述该类的功能]
 */
@Data
@Builder
@ToString
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class RestResult<T> implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    // 状态码
    private Integer code;
    // 消息
    private String message;
    // 数据
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private T data;
    // 请求结果生成的时间戳
    private Instant time = ZonedDateTime.now().toInstant();

    public static <T> RestResult<T> of(Integer code, String message, T data) {
        return new RestResult<>(code, message, data, ZonedDateTime.now().toInstant());
    }

    public static <T> RestResult<T> of(ExceptionSupport exception, T data) {
        return of(exception.getCode(), exception.getMessage(), data);
    }

    public static <T> RestResult<T> success(T data) {
        return of(ExceptionEnum.SUCCESS, data);
    }

    public static <T> RestResult<T> failed(T data) {
        return of(ExceptionEnum.INTERNAL_SERVER_ERROR, data);
    }
}
